package datastructure.sort;

import java.util.Arrays;

/**
 * @author wangmaolin1
 * @date 2023/11/11 13:57
 */
public class MergeSort2 {
    // 用于辅助合并有序数组
    private static int[] temp;

    public static void sort(int[] nums) {
        // 先给辅助数组开辟内存空间
        temp = new int[nums.length];
        // 排序整个数组（原地修改）
        sort(nums, 0, nums.length - 1);
    }

    private static void sort(int[] nums, int start, int end) {
        if (start >= end) {
            return;
        }
        int mid = start + (end - start) / 2;
        sort(nums, start, mid);
        sort(nums, mid + 1, end);
        merge(nums, start, mid, end);
    }

    private static void merge(int[] nums, int start, int mid, int end) {

        for (int i = start; i <= end; i++) {
            temp[i] = nums[i];
        }
        int lstart = start;
        int lend = mid;
        int rstart = mid + 1;
        int rend = end;
        for (int i = start; i <= end; i++) {
            if (lstart == mid+1) {
                nums[i] = temp[rstart++];
            } else if (rstart > rend) {
                nums[i] = temp[lstart++];
            } else if (temp[lstart] > temp[rstart]) {
                nums[i] = temp[rstart++];
            } else {
                nums[i] = temp[lstart++];
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[]{34, 235, 1, 4, 52, 574, 7, 21, 1};
        sort(arr);
        Arrays.stream(arr).forEach(System.out::println);

    }
}
